package acme.ws;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import acme.entity.Order;

public class OAuthAuthorizationServlet extends JSONServlet {

	private static final long serialVersionUID = 8875392317087332094L;

	public static String clientID = "";
	public static String scope = "";
	public static String redirectURI = "";
	public static String clientSecret = "";
	public static String authCode = "";
	public static String areaID = "258";

	// Incoming request for AuthCode
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		clientID = request.getParameter("client_id");

		scope = request.getParameter("scope");
		redirectURI = request.getParameter("redirect_uri");
		if (redirectURI == null || scope == null || clientID == null) {

			throw new RuntimeException(
					"Missing either client_id, redirect_uri, or scope");

		}
		InputStream input = getServletContext().getResourceAsStream(
				"Login.html");
		String html = "";
		int content;
		while ((content = input.read()) != -1) {
			// convert to char and display it
			html = html + (char) content;
		}

		String areaID = "258";
		String appName = TestAPI.masheryAPIFetchApp(clientID, areaID);

		String AuthCode = "12345";
		// String appName = "Jon's App";
		String redirect = redirectURI;
		html = html.replace("XRedirectX", redirect);

		html = html.replace("XapplicationNameX", appName);
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println(html);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		// Login page has posted username and password.
		// Assume successful.
		// Fetch Auth Code.
		if (req.getParameter("allow") != null) {
			resp.sendRedirect(redirectURI + "?error=access_denied");
		}

		String authCode = TestAPI.masheryAPIFetchAuthCode(clientID, areaID,
				redirectURI, scope);

		resp.sendRedirect(redirectURI + "?code=" + authCode);
		// Redirect to redirect URI with Auth code.

	}

}
